#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"

/*采用霍纳算法进行哈希化
 *
 *
 */
int64_t Hash(char *key)
{
	int i;
   	int64_t result = 0;
	
	for (i = 0; i < strlen(key); i++)
	{
		result = result * 37 + key[i];
	}
	return result % HASHLENGTH;
}


void hashmap_create()
{
	for (int i = 0; i < HASHLENGTH; i++)
	{
		arr[i].first = NULL;
		arr[i].last = NULL;
	}
	
	while (1)
	{
		Datatype vaule;
		char key[KEYSIZE] = {0};
		printf("请输入键值对\n");
		scanf("%s%*c%d",key,&vaule);
		if(*key == '#')
			break;
		hashmap_insert(key,vaule);
/*
		int ret, i;
		Datatype vaule;
		node_st *newnode = NULL;

		newnode = malloc(sizeof(node_st));
		if (newnode == NULL)
		{
			fprintf(stderr,"malloc()\n");
			exit(1);
		}

		for (i = 0;key[i] != '\n' && key[i]; i++)
			newnode->key[i] = key[i];
		newnode->vaule = vaule;
		newnode->next = NULL;

		ret = Hash(newnode->key);
		if (arr[ret].first == NULL)
		{
			arr[ret].first = newnode;
			arr[ret].last = newnode;
		}
		else
		{
			arr[ret].last->next = newnode;
			arr[ret].last = newnode;
		}
*/
	}
}

void hashmap_insert(char *key,Datatype vaule)
{
	int ret, i;
	Datatype value;

	node_st *newnode = NULL;
	newnode = malloc(sizeof(node_st));
	if (newnode == NULL)
	{
		fprintf(stderr,"malloc()\n");
		exit(1);
	}

	for (i = 0;key[i] != '\n' && key[i]; i++)
		newnode->key[i] = key[i];
	newnode->vaule = vaule;
	newnode->next = NULL;

	ret = Hash(newnode->key);
	if (arr[ret].first == NULL)
	{
		arr[ret].first = newnode;
		arr[ret].last = newnode;
	}
	else
	{
		arr[ret].last->next = newnode;
		arr[ret].last = newnode;
	}

}

static node_st *hashmap_find_(char *key)
{
	int ret;
	ret = Hash(key);

	node_st *p = NULL;
	for (p = arr[ret].first; p != NULL; p = p->next)
	{
		if (strcmp(p->key,key) == 0)
			return p;
	}
	return NULL;
}

int hashmap_find(char *key)
{
	node_st *p = NULL;
	if ((p = hashmap_find_(key)) != NULL)
		return p->vaule;
	return -1;
}

void hashmap_print()
{
	int i;
	node_st *p = NULL;
	for (i = 0; i < HASHLENGTH; i++)
	{
		for (p = arr[i].first; p != NULL; p = p->next)
			printf("%d->>",p->vaule);
		printf("\n");
	}

}

void hashmap_delete(char *key)
{
	int ret;
	ret = Hash(key);

	node_st *p = NULL;
	node_st *prev = NULL;
	for (p = arr[ret].first; p != NULL; p = p->next)
	{
		if (strcmp(p->key,key) == 0)
			break;
		prev = p;
	}

	if (p != NULL)
	{
		if(p == arr[ret].first)
		{
			arr[ret].first = p->next;
		}
		else
		{
			prev->next = p->next;
		}
		free(p);
	}
}
